/*!
 * \file MechManiaClient.cxx
 * \brief Implements the MechManiaClient class.
 */

#include "MechManiaClient.h"

using namespace Networking;
using namespace std;

MechManiaClient::MechManiaClient() : m_receivingBuffer( NULL )
{
	// Create our socket
	try
	{
		this->m_socket = new TcpSocket();
	}
	catch ( SocketException e )
	{
		cout << e.what () << endl;
	}
}

MechManiaClient::MechManiaClient( TcpSocket* socket ) : m_receivingBuffer( NULL )
{
	this->m_socket = socket;
}

MechManiaClient::~MechManiaClient ()
{
	if ( this->m_receivingBuffer != NULL )
	{
		delete[] this->m_receivingBuffer;
	}

	this->m_socket->Shutdown();
	delete this->m_socket;
}

void MechManiaClient::Connect( const std::string& ip, unsigned short port )
{
	this->m_socket->Connect( ip.c_str(), port );
}

void MechManiaClient::Listen( unsigned short port )
{
	this->m_socket->Listen( port );
}

MechManiaClient * MechManiaClient::Accept()
{
	return new MechManiaClient( this->m_socket->Accept() );
}

std::string MechManiaClient::ReceiveTurn()
{
	char lengthBuffer[ MechManiaClient::MessageSizeLength + 1 ];
	char * messageBuffer;
	int length = 0;

	try
	{
		this->m_socket->ReceiveAll( lengthBuffer, MechManiaClient::MessageSizeLength );
		lengthBuffer[ MechManiaClient::MessageSizeLength ] = '\0';
	}
	catch ( std::string duff )
	{
		return std::string();
	}

	length = atoi( lengthBuffer );


	// We now have a message length, allocate buffer
	messageBuffer = this->AllocateMessageBuffer( length );

	this->m_socket->ReceiveAll( messageBuffer, length );
	std::string xmlMessage( messageBuffer );

//	std::cout << xmlMessage << endl;
	return xmlMessage;
}

void MechManiaClient::SendTurn( const std::string & xmlMessage )
{
	std::ostringstream length;
	length << std::setw( MechManiaClient::MessageSizeLength ) << std::setfill( '0' ) << xmlMessage.length();

	this->m_socket->Send( length.str().c_str(), MechManiaClient::MessageSizeLength );
	this->m_socket->Send( xmlMessage.c_str(), ( unsigned int ) xmlMessage.length() );
}

char * MechManiaClient::AllocateMessageBuffer( long size )
{
	if ( this->m_receivingBuffer == NULL )
	{
		//std::cout << "Allocating buffer of size " << size + 1 << std::endl;
		this->m_receivingBuffer = new char[ size + 1 ];
		this->m_receivingBufferLength = size;
	}
	else if ( this->m_receivingBufferLength < size )
	{
		delete [] this->m_receivingBuffer;
		this->m_receivingBuffer = NULL;

		return this->AllocateMessageBuffer( size );
	}

	this->m_receivingBuffer[ size ] = '\0';

	return this->m_receivingBuffer;
}
